﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Windows.Input;
using System.ComponentModel;
using HandyControl.Controls;
using HandyControl.Data;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows.Threading;
using App2Wpf.Models;
using System.Threading;
using App2Wpf.Views;
using System.Windows;

namespace App2Wpf.ViewModels
{
    /// <summary>
    /// writeableBitmap 属性绑定
    /// System.ArgumentException: 必须在与 DependencyObject 相同的线程上创建 DependencySource。
    /// </summary>
    public class cardTestVM:ObservableObject
    {

        public static object locker = new object();

        public int id;
        public cardTestVM(nameip serverinfo)
        {

            //_close = new RelayCommand(new Action(_Open));

            //_close = new RelayCommand(new Action(_Close));
            //LoadingG.Visibility = Visibility.Visible;
            //ServiceLocator.firstVM.ConnectEvent += this.AddControlCard;

            this.ConnectServer = serverinfo;
            this.iPAddress = System.Net.IPAddress.Parse(serverinfo.ip);

            //CloseSmallCard = new RelayCommand(() => closeClicked());
            
        }

        public delegate void closeCardHandle(cardTestVM vm);

        public event closeCardHandle onClose;


        public nameip ConnectServer;

        public System.Net.IPAddress iPAddress;


        public ViewerBase _view;

        public ViewerBase view
        {
            get
            {
                return _view;
            }
            set
            {
                SetProperty(ref _view, value);
            }
        }

        public WriteableBitmap _wBitmap;
        public WriteableBitmap wBitmap
        {
            get => _wBitmap;
            set
            {
                SetProperty(ref _wBitmap, value);
            }
        }

        public BitmapSource _renderTargetBitmap;
        public BitmapSource crenderTargetBitmap
        {
            get => _renderTargetBitmap;
            set
            {
                SetProperty(ref _renderTargetBitmap, value);
            }
        }

        public RelayCommand ClosetheCard
        {
            get => new RelayCommand(()=> {
                //onClose(this);
                view.IsStop = true;         ////先给停止标志
                Thread.Sleep(50);           ////等待工作线程判断标志
                if ( null != view.remoteWin) view .remoteWin.Close();
                if ( null != view.session) view.session.CloseSession();
                ServiceLocator.rightWrapVM.removeCardById(this.id);
            }
            );
        }
       
        public void Refresh()
        {
            ////初始化对象 字节值 均为0 呈现为一个 大的黑色矩形
            //this.wBitmap = new WriteableBitmap(1920,1152 + 1, 96, 96, PixelFormats.Bgr32, null);

            switch (ServiceLocator.firstVM.ChooseCardMode)
            {
                //veryfast
                case RenderingMode.DrawVisual:
                    view = new ViewerRender(iPAddress, ConnectServer);
                    break;
                case RenderingMode.CardVMTest:
                    view = new ViewerTest(iPAddress, ConnectServer);
                    //view.onRendering += ViewR_refreshCard2;
                    break;
                case RenderingMode.DrawingGroup:
                    view = new ViewerDrawingGroup(iPAddress, ConnectServer);
                    break;
                case RenderingMode.Unsafe:
                    view = new ViewerRenderUnsafe(iPAddress, ConnectServer);
                    break;
                case RenderingMode.render3:
                    view = new ViewerRender3(iPAddress, ConnectServer);
                    break;

                default:
                    view = new ViewerBase(iPAddress, ConnectServer);  //very slow
                    break;

            }


            //viewR.OnConnect += () => {
            //    Dispatcher.Invoke(new Action(() =>
            //    {
            //        LoadingG.Visibility = Visibility.Collapsed;
            //        MiniWindow.Visibility = Visibility.Visible;
            //    }));
            //};
            //view.onRendering += ViewWindow_refreshCard;
            
            Task.Run(() => view.init(iPAddress)); //for loading not wait

        }
            private void ViewWindow_refreshCard(byte[] tempBuffer, System.Windows.Int32Rect tempRect)
        {
            // 调用线程无法访问此对象，因为另一个线程拥有该对象。对象被占用
            App.Current.Dispatcher.Invoke(new Action(() =>
            {
                this.wBitmap.Lock();
                System.Runtime.InteropServices.Marshal.Copy(tempBuffer, 0, this.wBitmap.BackBuffer, tempBuffer.Length);
                wBitmap.AddDirtyRect(tempRect);
                wBitmap.Unlock();
            }));
        }

        #region 鼠标键盘事件
        public void MiniWindow_MouseDown(object sender, MouseButtonEventArgs e)
        {
            
        }

        private void MiniWindow_MouseUp(object sender, MouseButtonEventArgs e)
        {

        }

        private void MiniWindow_MouseMove(object sender, MouseEventArgs e)
        {

        }

        private void MiniWindow_MouseWheel(object sender, MouseWheelEventArgs e)
        {

        }

        private void MiniWindow_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void MiniWindow_KeyUp(object sender, KeyEventArgs e)
        {

        }
        #endregion


        public RelayCommand OpenControlWindow
        {
            get => new RelayCommand(() => {
                Forms.ViewerControl sessionControlViewer = new Forms.ViewerControl(this.iPAddress, this.ConnectServer);
                sessionControlViewer.VirtualDeskForm.Show();
            }
            );
        }

        public RelayCommand OpenControlWindow2
        {
            get => new RelayCommand(() => {
                (view as ViewerRender).initShowBigWindow();
                view.IsShowControlWindow = true;
            });
        }
    }
}
